package cn.webrx.shiro;

import com.alibaba.druid.pool.DruidDataSource;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

/**
 * <p>功能描述: </p>
 *
 * @author webrx
 * @version 1.0
 * @date 2020-06-09 16:18
 */
public class Md5Realm extends AuthorizingRealm {
    //授权
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection pc) {
        return null;
    }

    //身份验证 认证
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //管理员
        String username = token.getPrincipal().toString();
        DruidDataSource ds = new DruidDataSource();
        ds.setUsername("root");
        ds.setPassword("");
        ds.setDriverClassName("com.mysql.cj.jdbc.Driver");
        ds.setUrl("jdbc:mysql:/db?serverTimezone=PRC");

        int state = 0;
        String password = "";
        try {
            Connection conn = ds.getConnection();
            PreparedStatement pst = conn.prepareStatement("select username,passwd from db_admin where username = ?");
            pst.setString(1, username);
            ResultSet rs = pst.executeQuery();
            if (rs.next()) {
                password = rs.getString("passwd");
            }else{
                state = 1;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        if(state == 1) throw new UnknownAccountException("账号不存在");
        if(state == 2) throw new LockedAccountException("账号锁定");
        if(state == 3) throw new DisabledAccountException("账号被禁用");
        //if(state == 4) throw new UnknownAccountException("账号不存在");

        //验证密码
        SimpleAuthenticationInfo sai = new SimpleAuthenticationInfo(username, password, ByteSource.Util.bytes(username), this.getName());
        return sai;
    }
}
